<template>
  <div class="device-dimension">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <el-icon class="is-loading" :size="40">
        <Loading />
      </el-icon>
      <p>正在加载设备数据...</p>
    </div>
    
    <!-- 设备核心指标 -->
    <div v-else class="kpi-group plan-metrics-group">
      <div class="kpi-group-header">
        <div class="header-left">
          <el-icon class="group-icon"><Monitor /></el-icon>
          <span class="group-title">设备核心指标</span>
          <el-tag type="info" size="small" class="metric-count">实时数据</el-tag>
        </div>
      </div>
      <div class="kpi-group-content">
        <el-row :gutter="16" class="metric-row">
          <el-col :span="6">
            <div class="kpi-card enhanced device-metric" @click="showMetricDetail('deviceCount')">
              <div class="kpi-card-inner">
                <div class="metric-icon-wrapper devices">
                  <el-icon><Monitor /></el-icon>
                </div>
                <div class="metric-content">
                  <div class="metric-name">设备总数</div>
                  <div class="metric-value-wrapper">
                    <transition name="number-fade" mode="out-in">
                      <span :key="deviceData?.planDeviceCount || 0" class="metric-main-value">
                        {{ deviceData?.planDeviceCount || 0 }}
                      </span>
                    </transition>
                    <span class="metric-unit">台</span>
                  </div>
                  <div class="device-status">
                    <span class="status-item running">运行 {{ getRunningDevices() }}</span>
                    <span class="status-item idle">空闲 {{ getIdleDevices() }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="kpi-card enhanced device-metric" @click="showMetricDetail('deviceUtilization')">
              <div class="kpi-card-inner">
                <div class="metric-icon-wrapper capacity">
                  <el-icon><Odometer /></el-icon>
                </div>
                <div class="metric-content">
                  <div class="metric-name">平均利用率</div>
                  <div class="metric-value-wrapper">
                    <transition name="number-fade" mode="out-in">
                      <span :key="deviceData?.avgDeviceCapacityRate || 0" class="metric-main-value">
                        {{ deviceData?.avgDeviceCapacityRate || 0 }}
                      </span>
                    </transition>
                    <span class="metric-unit">%</span>
                  </div>
                  <div class="utilization-mini-gauge" ref="utilizationMiniGauge"></div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="kpi-card enhanced device-metric" @click="showMetricDetail('deviceLoad')">
              <div class="kpi-card-inner">
                <div class="metric-icon-wrapper load">
                  <el-icon><TrendCharts /></el-icon>
                </div>
                <div class="metric-content">
                  <div class="metric-name">负载均衡度</div>
                  <div class="metric-value-wrapper">
                    <transition name="number-fade" mode="out-in">
                      <span :key="getLoadBalance()" class="metric-main-value">
                        {{ getLoadBalance() }}
                      </span>
                    </transition>
                    <span class="metric-unit">%</span>
                  </div>
                  <div class="metric-trend">
                    <span :class="['trend-badge', getLoadBalanceStatus()]">
                      {{ getLoadBalanceText() }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="kpi-card enhanced device-metric" @click="showMetricDetail('deviceEfficiency')">
              <div class="kpi-card-inner">
                <div class="metric-icon-wrapper efficiency">
                  <el-icon><Cpu /></el-icon>
                </div>
                <div class="metric-content">
                  <div class="metric-name">生产效率</div>
                  <div class="metric-value-wrapper">
                    <transition name="number-fade" mode="out-in">
                      <span :key="getProductionEfficiency()" class="metric-main-value">
                        {{ getProductionEfficiency() }}
                      </span>
                    </transition>
                    <span class="metric-unit">%</span>
                  </div>
                  <div class="efficiency-indicator">
                    <el-icon class="indicator-icon"><Lightning /></el-icon>
                    <span>高效运转</span>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 详细分析图表组 -->
    <div v-if="!loading" class="kpi-group analysis-group">
      <div class="kpi-group-header">
        <div class="header-left">
          <el-icon class="group-icon"><TrendCharts /></el-icon>
          <span class="group-title">设备负载分析</span>
        </div>
      </div>
      <div class="kpi-group-content">
        <div class="analysis-content">
          <el-row :gutter="16">
            <el-col :span="12">
              <div class="chart-card enhanced">
                <div class="chart-header">
                  <h4>各设备产能利用率</h4>
                  <el-button type="text" size="small" @click="showFullScreenChart('capacity')">
                    <el-icon><FullScreen /></el-icon>
                  </el-button>
                </div>
                <div class="chart-body">
                  <div class="sub-chart" ref="deviceCapacityChart"></div>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="chart-card enhanced">
                <div class="chart-header">
                  <h4>各设备计划利用率</h4>
                  <el-button type="text" size="small" @click="showFullScreenChart('plan')">
                    <el-icon><FullScreen /></el-icon>
                  </el-button>
                </div>
                <div class="chart-body">
                  <div class="sub-chart" ref="devicePlanChart"></div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <!-- 全屏图表对话框 -->
    <el-dialog
      v-model="fullScreenVisible"
      :title="fullScreenTitle"
      width="90%"
      :before-close="closeFullScreen"
      class="fullscreen-chart-dialog"
    >
      <div class="fullscreen-chart-container" ref="fullScreenChart"></div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Monitor,
  Odometer,
  TrendCharts,
  Cpu,
  Lightning,
  FullScreen,
  Loading
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { generateKPIData, generateDeviceUtilizationData } from '@/mock/kpiMockData'
import { planComparisonApi } from '@/api/planComparison'

export default {
  name: 'DeviceDimension',
  components: {
    Monitor,
    Odometer,
    TrendCharts,
    Cpu,
    Lightning,
    FullScreen,
    Loading
  },
  props: {
    constraintId: {
      type: [String, Number],
      default: null
    }
  },
  emits: ['metric-detail'],
  setup(props, { emit }) {
    // 数据
    const deviceData = ref(null)
    const loading = ref(false)
    
    // 图表 refs
    const deviceCapacityChart = ref(null)
    const devicePlanChart = ref(null)
    const utilizationMiniGauge = ref(null)
    const fullScreenChart = ref(null)
    
    // 全屏相关
    const fullScreenVisible = ref(false)
    const fullScreenTitle = ref('设备产能利用率')
    let fullScreenChartInstance = null
    let deviceCapacityChartInstance = null
    let devicePlanChartInstance = null
    let currentFullScreenType = 'capacity'
    
    // 计算属性
    const getRunningDevices = () => {
      const total = deviceData.value?.planDeviceCount || 0
      return Math.floor(total * 0.7)
    }
    
    const getIdleDevices = () => {
      const total = deviceData.value?.planDeviceCount || 0
      const running = getRunningDevices()
      return total - running
    }
    
    const getLoadBalance = () => {
      return Math.floor(Math.random() * 15) + 80
    }
    
    const getLoadBalanceStatus = () => {
      const balance = getLoadBalance()
      if (balance >= 90) return 'success'
      if (balance >= 70) return 'neutral'
      return 'danger'
    }
    
    const getLoadBalanceText = () => {
      const balance = getLoadBalance()
      if (balance >= 90) return '均衡良好'
      if (balance >= 70) return '基本均衡'
      return '需优化'
    }
    
    const getProductionEfficiency = () => {
      return Math.floor(Math.random() * 10) + 85
    }
    
    // 加载设备维度数据
    const loadDeviceData = async () => {
      if (!props.constraintId) {
        console.warn('约束ID不存在，使用Mock数据')
        deviceData.value = generateKPIData()
        await nextTick()
        initCharts()
        return
      }
      
      try {
        loading.value = true
        // TODO: 调用后端接口获取设备维度数据
        // const res = await planComparisonApi.getDeviceDimensionData(props.constraintId)
        // if (res && res.success) {
        //   deviceData.value = res.data
        // } else {
        //   // 使用Mock数据作为fallback
        //   deviceData.value = generateKPIData()
        // }
        
        // 暂时使用Mock数据
        deviceData.value = generateKPIData()
        
        await nextTick()
        initCharts()
      } catch (error) {
        console.error('加载设备维度数据失败:', error)
        ElMessage.error('加载设备数据失败')
        // 使用Mock数据作为fallback
        deviceData.value = generateKPIData()
        await nextTick()
        initCharts()
      } finally {
        loading.value = false
      }
    }
    
    // 初始化图表
    const initCharts = async () => {
      await nextTick()
      setTimeout(() => {
        initDeviceCapacityChart()
        initDevicePlanChart()
      }, 300)
    }
    
    // 初始化设备产能利用率图表
    const initDeviceCapacityChart = () => {
      if (!deviceCapacityChart.value || !deviceData.value?.deviceCapacityData) {
        console.warn('设备产能利用率图表 DOM 元素或数据不存在')
        return
      }
      
      try {
        // 如果已存在实例，先销毁
        if (deviceCapacityChartInstance) {
          deviceCapacityChartInstance.dispose()
        }
        
        deviceCapacityChartInstance = echarts.init(deviceCapacityChart.value)
        const data = deviceData.value.deviceCapacityData
        
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: '{b}: {c}%'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: data.map(item => item.name),
            axisLabel: {
              interval: 0,
              rotate: 30,
              fontSize: 11
            }
          },
          yAxis: {
            type: 'value',
            max: 100,
            axisLabel: {
              formatter: '{value}%',
              fontSize: 11
            }
          },
          series: [
            {
              name: '产能利用率',
              type: 'bar',
              barWidth: '60%',
              data: data.map(item => item.value),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#409EFF' },
                  { offset: 1, color: '#66B1FF' }
                ]),
                borderRadius: [4, 4, 0, 0]
              },
              label: {
                show: true,
                position: 'top',
                formatter: '{c}%',
                fontSize: 10
              }
            }
          ]
        }
        
        deviceCapacityChartInstance.setOption(option)
        
        // 自适应窗口大小
        const resizeHandler = () => {
          if (deviceCapacityChartInstance) {
            deviceCapacityChartInstance.resize()
          }
        }
        window.addEventListener('resize', resizeHandler)
      } catch (error) {
        console.error('设备产能利用率图表初始化错误:', error)
      }
    }
    
    // 初始化设备计划利用率图表
    const initDevicePlanChart = () => {
      if (!devicePlanChart.value || !deviceData.value?.devicePlanData) {
        console.warn('设备计划利用率图表 DOM 元素或数据不存在')
        return
      }
      
      try {
        // 如果已存在实例，先销毁
        if (devicePlanChartInstance) {
          devicePlanChartInstance.dispose()
        }
        
        devicePlanChartInstance = echarts.init(devicePlanChart.value)
        const data = deviceData.value.devicePlanData
        
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: '{b}: {c}%'
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: data.map(item => item.name),
            axisLabel: {
              interval: 0,
              rotate: 30,
              fontSize: 11
            }
          },
          yAxis: {
            type: 'value',
            max: 100,
            axisLabel: {
              formatter: '{value}%',
              fontSize: 11
            }
          },
          series: [
            {
              name: '计划利用率',
              type: 'bar',
              barWidth: '60%',
              data: data.map(item => item.value),
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#67C23A' },
                  { offset: 1, color: '#85CE61' }
                ]),
                borderRadius: [4, 4, 0, 0]
              },
              label: {
                show: true,
                position: 'top',
                formatter: '{c}%',
                fontSize: 10
              }
            }
          ]
        }
        
        devicePlanChartInstance.setOption(option)
        
        // 自适应窗口大小
        const resizeHandler = () => {
          if (devicePlanChartInstance) {
            devicePlanChartInstance.resize()
          }
        }
        window.addEventListener('resize', resizeHandler)
      } catch (error) {
        console.error('设备计划利用率图表初始化错误:', error)
      }
    }
    
    // 显示指标详情
    const showMetricDetail = (metricType) => {
      emit('metric-detail', metricType)
    }
    
    // 显示全屏图表
    const showFullScreenChart = (type) => {
      currentFullScreenType = type
      const chartInstance = type === 'capacity' ? deviceCapacityChartInstance : devicePlanChartInstance
      
      if (!chartInstance) {
        ElMessage.warning('图表未初始化')
        return
      }
      
      fullScreenVisible.value = true
      fullScreenTitle.value = type === 'capacity' ? '各设备产能利用率' : '各设备计划利用率'
      
      nextTick(() => {
        if (!fullScreenChart.value) return
        
        // 获取原图表的配置
        const option = chartInstance.getOption()
        
        // 创建全屏图表实例
        if (fullScreenChartInstance) {
          fullScreenChartInstance.dispose()
        }
        fullScreenChartInstance = echarts.init(fullScreenChart.value)
        fullScreenChartInstance.setOption(option)
        fullScreenChartInstance.resize()
        
        // 监听窗口大小变化
        const resizeHandler = () => {
          if (fullScreenChartInstance) {
            fullScreenChartInstance.resize()
          }
        }
        window.addEventListener('resize', resizeHandler)
      })
    }
    
    // 关闭全屏
    const closeFullScreen = () => {
      if (fullScreenChartInstance) {
        fullScreenChartInstance.dispose()
        fullScreenChartInstance = null
      }
      fullScreenVisible.value = false
    }
    
    // 生命周期
    onMounted(() => {
      loadDeviceData()
    })
    
    onUnmounted(() => {
      if (deviceCapacityChartInstance) {
        deviceCapacityChartInstance.dispose()
      }
      if (devicePlanChartInstance) {
        devicePlanChartInstance.dispose()
      }
      if (fullScreenChartInstance) {
        fullScreenChartInstance.dispose()
      }
    })
    
    // 监听 constraintId 变化
    watch(() => props.constraintId, () => {
      loadDeviceData()
    })
    
    return {
      deviceData,
      loading,
      deviceCapacityChart,
      devicePlanChart,
      utilizationMiniGauge,
      fullScreenChart,
      fullScreenVisible,
      fullScreenTitle,
      getRunningDevices,
      getIdleDevices,
      getLoadBalance,
      getLoadBalanceStatus,
      getLoadBalanceText,
      getProductionEfficiency,
      showMetricDetail,
      showFullScreenChart,
      closeFullScreen
    }
  }
}
</script>

<style scoped>
.device-dimension {
  width: 100%;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #909399;
}

.loading-state p {
  margin-top: 15px;
  font-size: 14px;
}

.kpi-group {
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  border-radius: 12px;
  padding: 1.5%;
  margin-bottom: 1.5%;
  border: 1px solid rgba(113, 75, 103, 0.08);
}

.kpi-group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(113, 75, 103, 0.06);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.group-icon {
  font-size: 24px;
  color: #714B67;
}

.group-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.metric-count {
  background: rgba(113, 75, 103, 0.08);
  border-color: rgba(113, 75, 103, 0.2);
  color: #714B67;
}

.metric-row {
  margin-bottom: 16px;
}

.kpi-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid rgba(113, 75, 103, 0.08);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  position: relative;
  overflow: hidden;
  height: 100%;
}

.kpi-card.enhanced {
  min-height: 120px;
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  display: flex;
  flex-direction: column;
}

.kpi-card-inner {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  flex: 1;
}

.metric-icon-wrapper {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  font-size: 24px;
}

.metric-icon-wrapper.devices {
  background: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.metric-icon-wrapper.capacity {
  background: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.metric-icon-wrapper.load {
  background: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.metric-icon-wrapper.efficiency {
  background: rgba(113, 75, 103, 0.1);
  color: #714B67;
}

.metric-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.metric-name {
  font-size: 13px;
  color: #909399;
  font-weight: 500;
}

.metric-value-wrapper {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.metric-main-value {
  font-size: 32px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
}

.metric-unit {
  font-size: 14px;
  color: #909399;
}

.device-status {
  display: flex;
  gap: 16px;
  margin-top: 8px;
}

.status-item {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.status-item::before {
  content: '';
  width: 6px;
  height: 6px;
  border-radius: 50%;
  display: inline-block;
}

.status-item.running::before {
  background: #67C23A;
}

.status-item.idle::before {
  background: #909399;
}

.utilization-mini-gauge {
  position: absolute;
  bottom: 8px;
  right: 8px;
  width: 50px;
  height: 25px;
  opacity: 0.6;
}

.metric-trend {
  display: flex;
  align-items: center;
  gap: 4px;
}

.trend-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.trend-badge.success {
  background: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.trend-badge.danger {
  background: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.trend-badge.neutral {
  background: rgba(144, 147, 153, 0.1);
  color: #909399;
}

.efficiency-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  font-size: 12px;
  color: #67C23A;
}

.indicator-icon {
  font-size: 16px;
}

/* 图表卡片 */
.chart-card {
  background: white;
  border-radius: 8px;
  border: 1px solid rgba(113, 75, 103, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-card.enhanced {
  min-height: 100%;
  height: 100%;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.2% 1.5%;
  border-bottom: 1px solid rgba(113, 75, 103, 0.06);
  background: linear-gradient(135deg, #fafbfc 0%, #f5f7fa 100%);
}

.chart-header h4 {
  margin: 0;
  font-size: 1.1vw;
  font-weight: 600;
  color: #303133;
}

.chart-body {
  padding: 1.2%;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.sub-chart {
  height: 100%;
  width: 100%;
  min-height: 300px;
  position: relative;
}

/* 全屏对话框 */
.fullscreen-chart-dialog :deep(.el-dialog__body) {
  padding: 20px;
  height: calc(90vh - 120px);
}

.fullscreen-chart-container {
  width: 100%;
  height: 100%;
  min-height: 600px;
}

/* 响应式布局 - 适配不同分辨率 */
@media screen and (min-width: 2560px) {
  .sub-chart {
    min-height: 320px;
  }
}

@media screen and (max-width: 1920px) {
  .sub-chart {
    min-height: 300px;
  }
}

@media screen and (max-width: 1440px) {
  .sub-chart {
    min-height: 280px;
  }
}

@media screen and (max-width: 1080px) {
  .sub-chart {
    min-height: 260px;
  }
}
</style>

